<template>
    <el-form :model="form" label-width="100px" ref="formRef">
      <el-form-item label="题目标题" prop="title" :rules="[{ required: true, message: '请输入题目标题', trigger: 'blur' }]">
        <el-input v-model="form.title" placeholder="请输入题目标题" />
      </el-form-item>
  
      <el-form-item label="题目内容" prop="content" :rules="[{ required: true, message: '请输入题目内容', trigger: 'blur' }]">
        <MdEditor v-model="form.content" language="zh-CN" />
      </el-form-item>
  
      <el-form-item label="标签">
        <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="选择或输入标签"
            style="width: 100%"
        >
          <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
          />
        </el-select>
      </el-form-item>
  
      <el-form-item label="答案">
        <el-input v-model="form.answer" type="textarea" :rows="4" placeholder="请输入答案" />
      </el-form-item>
  
      <el-form-item label="判题配置">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间限制(ms)" prop="judgeConfig.timeLimit">
              <el-input-number v-model="form.judgeConfig.timeLimit" :min="1" :max="10000" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内存限制(KB)" prop="judgeConfig.memoryLimit">
              <el-input-number v-model="form.judgeConfig.memoryLimit" :min="1" :max="256000" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="栈限制(KB)" prop="judgeConfig.stackLimit">
              <el-input-number v-model="form.judgeConfig.stackLimit" :min="1" :max="10000" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
  
      <el-form-item label="测试用例">
        <div v-for="(caseItem, index) in form.judgeCases" :key="index" style="margin-bottom: 16px; padding: 16px; border: 1px solid #dcdfe6; border-radius: 4px;">
          <el-form-item :label="`用例 ${index + 1}`">
            <el-button type="danger" size="small" @click="removeCase(index)" style="float: right;">删除</el-button>
          </el-form-item>
          <el-form-item label="输入">
            <el-input v-model="caseItem.input" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="输出">
            <el-input v-model="caseItem.output" type="textarea" :rows="3" />
          </el-form-item>
        </div>
        <el-button type="primary" @click="addCase">添加测试用例</el-button>
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { MdEditor } from 'md-editor-v3'
  import 'md-editor-v3/lib/style.css'
import type { QuestionVO, QuestionAdminVO, QuestionAddRequest, QuestionUpdateRequest, JudgeCase, JudgeConfig } from '../../../generated'

const props = defineProps<{
  question?: QuestionVO | QuestionAdminVO | null
}>()
  
  const emit = defineEmits<{
    submit: [data: QuestionAddRequest | QuestionUpdateRequest]
    cancel: []
  }>()
  
  const formRef = ref()
  
  const commonTags = ['数组', '字符串', '动态规划', '回溯', '贪心', '树', '图', '哈希表', '双指针', '排序']
  
  const form = reactive<{
    title: string
    content: string
    tags: string[]
    answer: string
    judgeConfig: JudgeConfig
    judgeCases: JudgeCase[]
  }>({
    title: '',
    content: '',
    tags: [],
    answer: '',
    judgeConfig: {
      timeLimit: 1000,
      memoryLimit: 128000,
      stackLimit: 128000,
    },
    judgeCases: [],
  })
  
  // 如果是编辑模式，填充表单
  watch(() => props.question, (question) => {
    if (question) {
      form.title = question.title || ''
      form.content = question.content || ''
      form.tags = question.tags || []
      form.answer = question.answer || ''
      form.judgeConfig = question.judgeConfig || {
        timeLimit: 1000,
        memoryLimit: 128000,
        stackLimit: 128000,
      }
      
      // 处理判题用例：QuestionAdminVO 使用 judgeCaseList，QuestionVO 使用 judgeCases
      if ('judgeCaseList' in question && question.judgeCaseList) {
        // QuestionAdminVO 类型
        form.judgeCases = question.judgeCaseList.map(caseItem => ({
          input: caseItem.input || '',
          output: caseItem.output || '',
        }))
      } else if ('judgeCases' in question && question.judgeCases) {
        // QuestionVO 类型
        form.judgeCases = question.judgeCases.map(caseItem => ({
          input: caseItem.input || '',
          output: caseItem.output || '',
        }))
      } else {
        form.judgeCases = []
      }
    } else {
      // 重置表单
      form.title = ''
      form.content = ''
      form.tags = []
      form.answer = ''
      form.judgeConfig = {
        timeLimit: 1000,
        memoryLimit: 128000,
        stackLimit: 128000,
      }
      form.judgeCases = []
    }
  }, { immediate: true })
  
  const addCase = () => {
    form.judgeCases.push({
      input: '',
      output: '',
    })
  }
  
  const removeCase = (index: number) => {
    form.judgeCases.splice(index, 1)
  }
  
  const handleSubmit = async () => {
    try {
      await formRef.value?.validate()
      emit('submit', { ...form })
    } catch (e) {
      console.error('表单验证失败', e)
    }
  }
  </script>